<?php
namespace Orx\Etl\Extractor\Source\Reader;
/**
 * Contact Import File Reader
 * Handle format translation
 *
 * @author Xavier VILAIN
 * @package Orx\Etl\Extractor\Source\Reader
 * @license #license-orx-etl#
 *
 */
class Csv {

	/**
	 * 
	 * Read the file expecting a spreadsheet 
	 * @param string $filename
	 * @param \Hive\Contact\Import\Format
	 */
	public static function read($filename,$format) {
		$limit = $format->attribute('row_limit');
		$delimiter = $format->attribute('delimiter');
		if(empty($delimiter)) {
			throw new \Exception('File delimiter is missing in the extractor');
		}
		$references = $errors = $data = array();
		// Open and Read File
		$rowCount = 1;
		$fields = $format->items();
		if (($handle = fopen($filename, 'r')) !== FALSE) {
		    while (($rowData = fgetcsv($handle, 1000,$delimiter)) !== FALSE) {
		    	if($rowCount == 1) {
		    		$rowCount++;
		    		continue;
		    	}
		    	$lineData = null;
		    	
			    foreach($fields as $id => $item) {
			    	$attribute = $item->attribute;
			    	$rule = $item->conversion_rule;
			    	if(empty($attribute)) {
			    		continue;
			    	}
			    	
			    	$colNumber = $item->position;
			    	$column = $item->position - 1;

			    	if($column == 20) {
			    		
			    	}
					// Get Cell Value
					if(!isset($rowData[$column])) {
						
						// File Format Error
						$errors[] = Msg(\Hive::BUNDLE,\Hive::ERR_EMPY_FIELD_IN_ROW_COLUMN,$rowCount,$colNumber,$item->label());
						break;
					}
					if(!empty($rule)) {
						$value = \Orx\Etl\Extractor\Source\Reader::convert($rowData[$column], $rowData, $rule);
						
					} else {
						// 
						$value = str_replace('"','',$rowData[$column]);
						switch ($item->datatype) {
							// Alpha numeric
							case 1:
								break;
							// Alpha numeric
							case 3:
								break;
							// Do nothing
							default;
						}
						// Check if the item is mandatory
						if($item->mandatory > 0 && empty($value)) {
							$errors[] = Msg(\Hive::BUNDLE,\Hive::ERR_EMPY_FIELD_IN_ROW_COLUMN,$rowCount,$colNumber,$item->label());
							break;
						}
					}
					$values = is_array($value) ? $value : array($item->reference.'_'.$item->sequence.'_'.$attribute => $value);
					
					foreach($values as $fieldname => $val) {
						// Parse Value & Check Format
						$parts = explode('_',$fieldname);
						$firstPart = $parts[0].'_'.$parts[1].'_';
						$tagertFieldName = substr($fieldname,strlen($firstPart));
						// Reference Data Line
						$lineData[$fieldname] = $val;
						$reference[$parts[0]][$parts[1]][$tagertFieldName] = $val;
					}
				}
				if(is_array($lineData)) {
					$data[] = $lineData;
					$references[] = $reference;
				}
		    }
		    fclose($handle);
		}
		return array('data' => $data,'errors' => $errors,'references' => $references);
	}
	
	/**
	 * 
	 * Parse First Line (Should Contain Headers)
	 * 
	 * @param string $filename
	 * @param Orx\Etl\Extractor\Source
	 * @return array
	 */
	public static function readFirstRow($filename,$format)  {
		$delimiter = $format->attribute('delimiter');
		if(empty($delimiter)) {
			throw new \Exception('Wrong File Format');
		}
		// Open and Read File
		if (($handle = fopen($filename, 'r')) !== FALSE) {
			$exit = false;
		    while (($rowData = fgetcsv($handle, 1000,$delimiter)) !== false && !$exit) {
		    	$exit = true;
		    	return $rowData;
		    }
		}
		return array();
	}
}